package com.bite.common.utils;

import io.netty.util.Timeout;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;


@Slf4j
public class Redis {
    private StringRedisTemplate redisTemplate;

    private final String REDIS_SPLIT=":";
    private final String REDIS_DEFAULT="default";

    public Redis(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    public String get(String key) {
        try{
            return key==null?null:redisTemplate.opsForValue().get(key);
        }catch (Exception e){
            log.error("redis get error,key:{}",key);
            return null;
        }
    }

    public boolean hasKey(String key) {
        try{
            return key==null?null:redisTemplate.hasKey(key);
        }catch (Exception e){
            log.error("redis hasKey error,key:{}",key);
            return false;
        }
    }

    public boolean set(String key, String value) {
        try{
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            log.error("redis set error,key:{},value:{}",key,value);
            return false;
        }
    }

    public boolean set(String key, String value,long timeout) {
        try{
            if (timeout > 0) {
                //设置过期时间，单位为秒
                redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception e){
            log.error("redis set error,key:{},value:{}",key,value);
            return false;
        }
    }

    public String buildKey(String prefix, String... args) {
        //1 张三  user:1:zhangsan
        if (prefix == null) {
            prefix = REDIS_DEFAULT;
        }

        StringBuilder key = new StringBuilder(prefix);
        key.append(prefix);

        if (args != null) {
            for (String arg : args) {
                key.append(REDIS_SPLIT).append(arg);
            }
        }
        return key.toString();
    }
}
